//
//  SAAddMemberVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/6/21.
//

#import "SAAddMemberVC.h"
#import "UILabel+NSMutableAttributedString.h"
#import "HDDatePickerView.h"
#import "SASystemEmpSearchAPI.h"
#import "SAMemberOptionAPI.h"
#import "SAStoreUserModel.h"
#import "BubbleTableView.h"
#import "SAMemberOptionModel.h"
#import "SAMemberSaveAPI.h"
#import "SAMemberListModel.h"
#import "SAMemberUpdateAPI.h"
#import "NSString+FintCommon.h"

@interface SAAddMemberVC ()<HTTPAPIDelegate>

@property (nonatomic, strong) SASystemEmpSearchAPI *systemEmpSearchAPI;
@property (nonatomic, strong) SAMemberOptionAPI *memberOptionAPI;
@property (nonatomic, strong) NSMutableArray<SAStoreUserModel *> *empMarr;
@property (nonatomic, strong) NSMutableArray<SAMemberOptionModel *> *memberMarr;

@property (nonatomic, strong) BubbleTableView *empBubbleView;
@property (nonatomic, strong) BubbleTableView *memberBubbleView;

@property (nonatomic, strong) UIButton *levelBtn;
@property (nonatomic, strong) UIButton *dateBtn;
@property (nonatomic, strong) UIButton *empBtn;

@property (nonatomic, strong) UITextField *nameTf;
@property (nonatomic, strong) UITextField *iphoneTf;
@property (nonatomic, strong) UITextField *levelTf;
@property (nonatomic, strong) UITextField *dateTf;
@property (nonatomic, strong) UITextField *userTf;
@property (nonatomic, strong) UITextField *addressTf;
@property (nonatomic, strong) UITextField *remarkTf;

@property (nonatomic, assign) NSInteger empRow;
@property (nonatomic, assign) NSInteger memberRow;
@property (nonatomic, strong) SAMemberSaveAPI *memberSaveAPI;
@property (nonatomic, strong) SAMemberUpdateAPI *memberUpdateAPI;

@property (nonatomic, strong) UIView *levelView;
@property (nonatomic, strong) UIView *empView;

@end

@implementation SAAddMemberVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.systemEmpSearchAPI == api) {
        self.empMarr = [SAStoreUserModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        if (self.model != nil) {
            for (int i = 0; i < self.empMarr.count; i++) {
                if ([self.empMarr[i].empName isEqualToString:self.model.empName]) {
                    self.empRow = i;
                }
            }
        }
    }else if (self.memberOptionAPI == api) {
        self.memberMarr = [SAMemberOptionModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        if (self.memberMarr.count > 0 && self.model == nil) {
            self.levelTf.text = self.memberMarr[0].name;
            self.memberRow = 0;
        }
        if (self.model != nil) {
            for (int i = 0; i < self.memberMarr.count; i++) {
                if ([self.memberMarr[i].name isEqualToString:self.model.memberLevelStr]) {
                    self.memberRow = i;
                }
            }
        }
    }else if (self.memberSaveAPI == api) {
        !self.refreshBlock ?: self.refreshBlock();
        [Prompt popPromptViewWithMsg:@"添加成功" duration:2];
        [self.navigationController popViewControllerAnimated:YES];
    }else if (self.memberUpdateAPI == api) {
        !self.refreshBlock ?: self.refreshBlock();
        [Prompt popPromptViewWithMsg:@"修改成功" duration:2];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    
}

#pragma mark - event
-(void)clickedCompleteBtn {
    if (trimString(self.nameTf.text).length == 0) {
        [Prompt popPromptViewWithMsg:@"请输入名称" duration:2];
        return;
    }else if (trimString(self.iphoneTf.text).length == 0) {
        [Prompt popPromptViewWithMsg:@"请输入手机号" duration:2];
        return;
    }else if (trimString(self.userTf.text).length == 0) {
        [Prompt popPromptViewWithMsg:@"请输入开卡人" duration:2];
        return;
    }
    
    NSString *empId = @"";
    if (self.empRow >= 0) {
        empId = self.empMarr[self.empRow].empId;
    }
    NSString *memberLevel = @"";
    if (self.memberRow >= 0) {
        memberLevel = self.memberMarr[self.memberRow].id;
    }
    
    if (self.model != nil) {        
        self.memberUpdateAPI.address = self.addressTf.text;
        self.memberUpdateAPI.empId = self.model.empId;
        self.memberUpdateAPI.memberLevel = memberLevel;
        self.memberUpdateAPI.mobile = self.iphoneTf.text;
        self.memberUpdateAPI.remark = self.remarkTf.text;
        self.memberUpdateAPI.memberName = self.nameTf.text;
        self.memberUpdateAPI.birthday = self.dateTf.text;
        self.memberUpdateAPI.memberId = self.model.memberId;
        self.memberUpdateAPI.merchantId = self.model.merchantId;
        [self.memberUpdateAPI sendRequestToServerWithActivityViewAndMask:POST];
    }else {
        self.memberSaveAPI.address = self.addressTf.text;
        self.memberSaveAPI.empId = empId;
        self.memberSaveAPI.memberLevel = memberLevel;
        self.memberSaveAPI.mobile = self.iphoneTf.text;
        self.memberSaveAPI.remark = self.remarkTf.text;
        self.memberSaveAPI.memberName = self.nameTf.text;
        self.memberSaveAPI.birthday = self.dateTf.text;
        [self.memberSaveAPI sendRequestToServerWithActivityViewAndMask:POST];
    }
}

-(void)clickedLevelBtn {
    if (self.memberMarr.count == 0) {
        [Prompt popPromptViewWithMsg:@"请先新增会员等级" duration:2];
        return;;
    }
    NSMutableArray *marr = [NSMutableArray array];
    for (SAMemberOptionModel *model in self.memberMarr) {
        if (model.name.length == 0) {
            model.name = @"";
        }
        [marr addObject:model.name];
    }
    NSInteger height = self.memberMarr.count * 50 + 10;
    if (height > 190) {
        height = 190;
    }
    NSArray *arr = nil;
    UIView *window = [UIApplication sharedApplication].keyWindow;
    if (!self.memberBubbleView) {
        self.memberBubbleView = [[BubbleTableView alloc] initWithLocation:(BubbleLocationDown) bubbleAlignment:(BubbleAlignmentRight) width:120 height:height cellClickBlock:^(NSInteger row, NSString * _Nonnull rowString, NSArray *fromDataArray) {
            self.memberRow = row;
            self.levelTf.text = rowString;
        } hideBlock:^{
            self.memberBubbleView = nil;
        }];
        
        [self.memberBubbleView showWithTargetView:self.levelView maskSuperView:window];
        [self.memberBubbleView updateBubble:marr fromDataArray:arr];// 更新气泡弹框
        self.memberBubbleView.bubbleCellHeight = 50;
        self.memberBubbleView.selectRow = self.memberRow;
        self.memberBubbleView.isBubbleScrollEnabled = YES;
        self.memberBubbleView.bubbleCellTextAlignment = NSTextAlignmentCenter;
    }
}

-(void)clickedDateBtn {
    WeakSelf
    NSString *date = self.dateTf.text;
    if (date.length == 0){
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        date = [dateFormatter stringFromDate:[NSDate date]];
    }
    HDDatePickerView *pickerView = [[HDDatePickerView alloc] initWithSlectedDate:date];
    [pickerView show];
    pickerView.selectDateBlock = ^(NSString *selectedDate) {
        weakSelf.dateTf.text = selectedDate;
    };
}

-(void)clickedEmpBtn {
    [self.view endEditing:YES];
    if (self.empMarr.count == 0) {
        [Prompt popPromptViewWithMsg:@"请先新增开卡人" duration:2];
        return;;
    }
    NSMutableArray *marr = [NSMutableArray array];
    for (SAStoreUserModel *model in self.empMarr) {
        if (model.empName.length == 0) {
            model.empName = @"";
        }
        [marr addObject:model.empName];
    }
    NSInteger height = self.empMarr.count * 50 + 10;
    if (height > 190) {
        height = 190;
    }
    NSArray *arr = nil;
    UIView *window = [UIApplication sharedApplication].keyWindow;
    if (!self.empBubbleView) {
        self.empBubbleView = [[BubbleTableView alloc] initWithLocation:(BubbleLocationDown) bubbleAlignment:(BubbleAlignmentRight) width:120 height:height cellClickBlock:^(NSInteger row, NSString * _Nonnull rowString, NSArray *fromDataArray) {
            self.empRow = row;
            self.userTf.text = rowString;
        } hideBlock:^{
            self.empBubbleView = nil;
        }];
        
        [self.empBubbleView showWithTargetView:self.empView maskSuperView:window];
        [self.empBubbleView updateBubble:marr fromDataArray:arr];// 更新气泡弹框
        self.empBubbleView.selectRow = self.empRow;
        self.empBubbleView.bubbleCellHeight = 50;
        self.empBubbleView.isBubbleScrollEnabled = YES;
        self.empBubbleView.bubbleCellTextAlignment = NSTextAlignmentCenter;
    }
}

- (void)textFieldEditChanged:(UITextField*)textField {
    NSString *newStr = [textField.text noEmoji];
    if (textField.text.length != newStr.length) {
        textField.text = newStr;
    }
}
#pragma mark - initUI
-(void)initUI {
    [self setNavigationItemBackBBIAndTitle:@"新增会员"];
    self.view.backgroundColor = kBgColor;
    
    self.empRow = -1;
    self.memberRow = -1;

    UIButton *completeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    completeBtn.frame = CGRectMake(0, 0, kScaleNum(60), kScaleNum(44));
    [completeBtn setTitle:@"完成" forState:UIControlStateNormal];
    completeBtn.titleLabel.font = kFont(16);
    [completeBtn setTitleColor:kBuleColor forState:UIControlStateNormal];
    [completeBtn addTarget:self action:@selector(clickedCompleteBtn) forControlEvents:UIControlEventTouchUpInside];
    [self addRightViews:@[completeBtn]];
    
    UIView *whiteView = [[UIView alloc] initWithFrame:SARectMake(0, StatusHeight + 5, kBaseScreenWidth, 286)];
    whiteView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:whiteView];
    
    NSArray *arr = @[@"*名称", @"*手机", @"等级", @"生日", @"*开卡人", @"地址", @"备注"];
    NSArray *arr2 = @[@"请输入名称", @"请输入手机号", @"普通会员", @"请选择生日", @"请选择开卡人", @"请输入地址", @"请输入备注"];
    for (int i = 0; i < arr.count; i++) {
        UILabel *titleLab = [[UILabel alloc] initWithFrame:SARectMake(20, 41 * i, 80, 40)];
        titleLab.text = arr[i];
        titleLab.textColor = kBlackColor;
        titleLab.font = kFont(15);
        [whiteView addSubview:titleLab];
        [titleLab setAttributedStringWithSubString:@"*" color:[UIColor redColor]];
        
        UITextField *inputTf = [[UITextField alloc] initWithFrame:SARectMake(150, 41 * i, 185, 40)];
        inputTf.textColor = kBlackColor;
        inputTf.font = kFont(15);
        inputTf.textAlignment = NSTextAlignmentLeft;
        inputTf.placeholder = arr2[i];
        inputTf.clearButtonMode = UITextFieldViewModeWhileEditing;
        [inputTf addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
        [whiteView addSubview:inputTf];
        
        if (i == 2 || i == 3 || i == 4) {
            UIView *levelView = [UIView new];
            levelView.frame =  SARectMake(335, 41 * i, 38, 40);
            [whiteView addSubview:levelView];
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = SARectMake(150, 41 * i, kBaseScreenWidth - 150, 40);
            [button setImage:[UIImage imageNamed:@"shop_grayAllow"] forState:UIControlStateNormal];
            [whiteView addSubview:button];
            inputTf.clearButtonMode = UITextFieldViewModeNever;
            inputTf.userInteractionEnabled = NO;
            if (i == 2) {
                [button addTarget:self action:@selector(clickedLevelBtn) forControlEvents:UIControlEventTouchUpInside];
                self.levelBtn = button;
                self.levelView = levelView;
            }else if (i == 3) {
                [button addTarget:self action:@selector(clickedDateBtn) forControlEvents:UIControlEventTouchUpInside];
                self.dateBtn = button;
            }else {
                [button addTarget:self action:@selector(clickedEmpBtn) forControlEvents:UIControlEventTouchUpInside];
                self.empBtn = button;
                self.empView = levelView;
            }
            button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
            button.imageEdgeInsets = kEdgeInsetsMake(0, 0, 0, 15);
            
            
        }

        UIView *line = [[UIView alloc] initWithFrame:SARectMake(0, 40 + 41 * i, kBaseScreenWidth, 1)];
        line.backgroundColor = kBgColor;
        [whiteView addSubview:line];
        
        if (i == 0) {
            self.nameTf = inputTf;
        }else if (i == 1) {
            self.iphoneTf = inputTf;
            inputTf.keyboardType = UIKeyboardTypeNumberPad;
        }else if (i == 2) {
            self.levelTf = inputTf;
        }else if (i == 3) {
            self.dateTf = inputTf;
        }else if (i == 4) {
            self.userTf = inputTf;
        }else if (i == 5) {
            self.addressTf = inputTf;
        }else if (i == 6) {
            self.remarkTf = inputTf;
        }
    }
    
    if (self.model != nil) {
        self.titleLab.text = @"基本信息";
        self.nameTf.text = self.model.memberName;
        self.iphoneTf.text = self.model.mobile;
        self.levelTf.text = self.model.memberLevelStr;
        self.dateTf.text = self.model.birthday;
        self.userTf.text = self.model.empName;
        self.addressTf.text = self.model.address;
        self.remarkTf.text = self.model.remark;
        self.empBtn.hidden = YES;
    }
    
    [self.systemEmpSearchAPI sendRequestToServerWithActivityViewAndMask:GET];
    [self.memberOptionAPI sendRequestToServerWithActivityViewAndMask:GET];
}

-(SASystemEmpSearchAPI *)systemEmpSearchAPI {
    if (!_systemEmpSearchAPI) {
        _systemEmpSearchAPI = [SASystemEmpSearchAPI apiWithDelegate:self];
    }
    return _systemEmpSearchAPI;
}

-(SAMemberOptionAPI *)memberOptionAPI {
    if (!_memberOptionAPI) {
        _memberOptionAPI = [SAMemberOptionAPI apiWithDelegate:self];
    }
    return _memberOptionAPI;
}

-(NSMutableArray<SAStoreUserModel *> *)empMarr {
    if (!_empMarr) {
        _empMarr = [NSMutableArray array];
    }
    return _empMarr;
}

-(NSMutableArray<SAMemberOptionModel *> *)memberMarr {
    if (!_memberMarr) {
        _memberMarr = [NSMutableArray array];
    }
    return _memberMarr;
}

-(SAMemberSaveAPI *)memberSaveAPI {
    if (!_memberSaveAPI) {
        _memberSaveAPI = [SAMemberSaveAPI apiWithDelegate:self];
    }
    return _memberSaveAPI;
}

-(SAMemberUpdateAPI *)memberUpdateAPI {
    if (!_memberUpdateAPI) {
        _memberUpdateAPI = [SAMemberUpdateAPI apiWithDelegate:self];
    }
    return _memberUpdateAPI;
}

@end
